package com.skyworthclub.competition.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.skyworthclub.competition.beans.Comment;
import com.skyworthclub.competition.mapper.CommentMapper;
import com.skyworthclub.competition.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.stereotype.Service;

import java.sql.Wrapper;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author li
 * @since 2018-10-15
 */
@Service
@CacheConfig(cacheNames = "competition-comments")
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {

    /**
     * 单页元素个数
     */
    private static final int PAGE_SIZE = 5;

    private final CommentMapper commentMapper;

    @Autowired
    public CommentServiceImpl(CommentMapper commentMapper) {
        this.commentMapper = commentMapper;
    }

    @Override
    public Page<Comment> getPage(Integer matchId, Integer pageNum) {
        Page<Comment> page = new Page<>(pageNum, PAGE_SIZE);
        List<Comment> commentList = commentMapper.selectCommentPage(page, matchId);
        page.setRecords(commentList);
        return page;
    }

    @Override
    public boolean insertComment(Comment comment) {
        comment.setCommentTime(LocalDateTime.now());
        return super.insert(comment);
    }

    @Override
    public boolean deleteCommentById(Integer id) {
        return super.deleteById(id);
    }

    @Override
    public boolean updateCommentById(Comment entity) {
        return super.updateById(entity);
    }

    @Override
    public Page<Comment> getTopComments(Integer matchId, Integer pageNum) {

        Page<Comment> page = new Page<>(pageNum, PAGE_SIZE * 2);
        EntityWrapper<Comment> wrapper = new EntityWrapper<>();
        wrapper.eq("match_id", matchId)
                .isNull("parent_id")
                .orderBy("comment_id", false);
        return super.selectPage(page, wrapper);
    }

    @Override
    public Page<Comment> getChildComments(Integer parentId, Integer pageNum) {

        Page<Comment> page = new Page<>(pageNum, PAGE_SIZE * 2);
        EntityWrapper<Comment> wrapper = new EntityWrapper<>();
        wrapper.eq("parent_id", parentId)
                .orderBy("comment_id", true);
        return super.selectPage(page, wrapper);

    }
}
